<script lang="ts" setup name="B12Watch4">
import { reactive, watch } from "vue";

const person = reactive({
  name: "张三",
  age: 18,
  car: {
    c1: "别墨我",
    c2: "大本",
  },
});

const changeName = () => {
  person.name += "~";
};
const changeAge = () => {
  person.age += 1;
};
const changeC1 = () => {
  person.car.c1 = "凹的";
};
const changeC2 = () => {
  person.car.c2 = "并言蒂";
};
const changeCar = () => {
  person.car = {
    c1: "泰陵",
    c2: "丫地",
  };
};

// 属性是基本数据类型
/*
watch(
  () => person.name,
  (nv, ov) => console.log(`姓名发生变化：${ov} -> ${nv}`),
);

watch(
  () => person.age,
  (nv, ov) => console.log(`年龄发生变化：${ov} -> ${nv}`),
);

watch(
  () => person.car.c1,
  (nv, ov) => console.log(`第一台车换了：${ov} => ${nv}`),
);
*/

// 属性是对象 【虽然可以直接写，但还是建议使用回调函数+deep的形式】
//watch(person.car, (nv, ov) =>
watch(
  () => person.car,
  (nv, ov) =>
    console.log(`换车了：${JSON.stringify(ov)} -> ${JSON.stringify(nv)}`),
  { deep: true },
);
</script>
<template>
  <h1 class="text-xl border-l-8 pl-3">
    情况四：监视reactive/ref定义的对象类型中的某个属性
  </h1>
  <div class="my-3">
    <div>姓名：{{ person.name }}</div>
    <div>年龄：{{ person.age }}</div>
    <div>车：{{ person.car.c1 }}, {{ person.car.c2 }}</div>
  </div>
  <div class="flex justify-start items-center gap-x-2">
    <button class="p-1 border shadow" @click="changeName">改名</button>
    <button class="p-1 border shadow" @click="changeAge">改年龄</button>
    <button class="p-1 border shadow" @click="changeC1">改第一台车</button>
    <button class="p-1 border shadow" @click="changeC2">改第二台车</button>
    <button class="p-1 border shadow" @click="changeCar">改电瓶车</button>
  </div>
</template>
